import { mabangOrderIndex } from "@/api/mabang";
import { type Ref, reactive, ref, onMounted, watch, h, createVNode } from "vue";
import { getKeyList, cloneDeep, isAllEmpty } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import { ElTag, ElText } from "element-plus";
import { addDrawer } from "@/components/ReDrawer";
import { deviceDetection } from "@pureadmin/utils";
import orderDetail from "../form/orderDetail.vue";
import { DocumentCopy } from "@element-plus/icons-vue";

// 时间格式化工具函数
function formatDateTime(timestamp: any): string {
  if (!timestamp || timestamp === 0 || timestamp === '0' || timestamp === '') {
    return '-';
  }

  try {
    let date: Date;

    // 判断是时间戳还是日期字符串
    if (typeof timestamp === 'string') {
      // 检查是否为纯数字字符串（时间戳）
      if (/^\d+$/.test(timestamp)) {
        // 是时间戳字符串
        const time = parseInt(timestamp);
        if (isNaN(time) || time <= 0) {
          return '-';
        }
        date = new Date(time * 1000);
      } else {
        // 是日期字符串，直接解析
        date = new Date(timestamp);
      }
    } else if (typeof timestamp === 'number') {
      // 是数字时间戳
      if (timestamp <= 0) {
        return '-';
      }
      date = new Date(timestamp * 1000);
    } else {
      return '-';
    }

    // 验证日期对象有效性
    if (isNaN(date.getTime())) {
      return '-';
    }

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (error) {
    console.error('时间格式化失败:', timestamp, error);
    return '-';
  }
}

export function useMabangOrders(tableRef: Ref) {
  const form = reactive({
    search_field: "id",
    search: '',
    order_status: '',
    shop_id: '', // 添加店铺筛选字段
    order_type: 'all', // 添加订单类型字段
    search_field2: '',
    time: '',
    page: 1,
    limit: 15,
    sort_field: '',
    sort_order: ''
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const searchCondList = ref([]);
  const orderStatusList = ref([]);
  const shopOptionsList = ref([]);

  // 订单类型tabs相关状态
  const activeTab = ref('all');
  const tabsList = ref([]);
  const tabCounts = ref({});

  // 防重复点击标志
  const isDrawerOpening = ref(false);

  // 打开详情抽屉
  function openOrderDetail(row: any) {
    // 防重复点击
    if (isDrawerOpening.value) {
      console.log('抽屉正在打开，忽略重复点击');
      return;
    }

    console.log('点击订单详情:', row);
    isDrawerOpening.value = true;

    addDrawer({
      size: '60%',
      title: `订单详情：${row.id}`,
      hideFooter: true,
      destroyOnClose: true, // 关闭时销毁组件
      closeDelay: 200, // 设置关闭延迟
      closeOnClickModal: true, // 点击遮罩关闭
      closeOnPressEscape: true, // 按ESC关闭
      closeCallBack: ({ options, index, args }) => {
        // 抽屉关闭后重置标志
        console.log('抽屉关闭回调，命令:', args?.command);
        setTimeout(() => {
          isDrawerOpening.value = false;
        }, 300);
      },
      contentRenderer: () =>
        createVNode(orderDetail, {
          formInline: {
            auto_id: row.auto_id,
            id: row.id
          }
        }),
    });

    // 设置打开标志的超时重置，防止异常情况
    setTimeout(() => {
      isDrawerOpening.value = false;
    }, 1000);
  }

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    pageSizes: [10, 20, 40, 60, 100, 200],
    currentPage: 1,
    background: true
  });

  // 表格列配置
  const columns = ref([
    {
      label: "勾选列",
      type: "selection",
      width: 50,
      disabled: true,
      fixed: true
    },
    {
      label: "订单ID",
      prop: "id",
      width: 80,
      align: "left",
      disabled: true,
      fixed: true,
      sortable: "custom",
      cellRenderer: ({ row }) => (
        <span
          style="color: var(--el-color-primary); cursor: pointer; text-decoration: underline; font-size: 12px;"
          onClick={(e) => {
            e.stopPropagation(); // 阻止事件冒泡
            console.log('点击订单ID:', row.id, row);
            openOrderDetail(row);
          }}
        >
          {row.id}
        </span>
      )
    },
    {
      label: "订单交易号",
      prop: "sales_record_number",
      width: 160,
      sortable: "custom",
      cellRenderer: ({ row, props }) => (
        <div style="display: flex; align-items: center; gap: 8px;">
          <span>{row.sales_record_number}</span>
          <el-button
            icon={DocumentCopy}
            size="small"
            type="primary"
            link
            title="点击复制"
            onClick={() => copycontent(row.sales_record_number)}
          />
        </div>
      )
    },

    {
      label: "订单编号",
      prop: "platform_order_id",
      width: 140,
      sortable: "custom",
      cellRenderer: ({ row, props }) => (
        <div style="display: flex; align-items: center; gap: 8px;">
          <span>{row.platform_order_id}</span>
          <el-button
            icon={DocumentCopy}
            size="small"
            type="primary"
            link
            title="点击复制"
            onClick={() => copycontent(row.platform_order_id)}
          />
        </div>
      )
    },
    {
      label: "支付时间",
      prop: "paid_time",
      width: 140,
      sortable: "custom",
      cellRenderer: ({ row }) => (
        <span>{formatDateTime(row.paid_time)}</span>
      )
    },
    {
      label: "店铺名称",
      prop: "shop_id_text",
      width: 120,
      showOverflowTooltip: true
    },
    {
      label: "买家姓名",
      prop: "buyer_name",
      width: 120,
      showOverflowTooltip: true
    },
    {
      label: "买家邮箱",
      prop: "email",
      width: 180,
      align: 'left',
      showOverflowTooltip: true
    },
    {
      label: "订单金额",
      prop: "order_fee_usd",
      width: 130,
      align: "right",
      cellRenderer: ({ row }) => (
        <span>{row.order_fee_usd ? `${row.order_fee_usd} USD` : '-'}</span>
      )
    },
    {
      label: "订单原始金额",
      prop: "order_fee_original",
      width: 100,
      align: "right",
      cellRenderer: ({ row }) => (
        <span>{row.order_fee_original} {row.currency_id}</span>
      )
    },
    {
      label: "订单状态",
      prop: "order_status",
      width: 100,
      cellRenderer: ({ row }) => {
        const statusMap = {
          '0': { type: 'warning', text: '待付款' },
          '1': { type: 'warning', text: '未审核' },
          '2': { type: 'info', text: '配货中' },
          '3': { type: 'primary', text: '已发货' },
          '4': { type: 'success', text: '已完成' },
          '5': { type: 'danger', text: '已取消' },
          '6': { type: 'primary', text: '部分发货' },
          '7': { type: 'danger', text: '已退款' },
          '8': { type: 'danger', text: '异常订单' },
          '9': { type: 'warning', text: '暂停发货' },
          '10': { type: 'info', text: '等待收货' },
          '11': { type: 'info', text: '部分收货' }
        };
        const status = statusMap[row.order_status] || { type: 'info', text: '未知' };
        return <ElTag type={status.type} size="small">{status.text}</ElTag>;
      }
    },
    {
      label: "国家",
      prop: "country_code_cn",
      width: 100
    },
    {
      label: "省份",
      prop: "province",
      width: 100,
      showOverflowTooltip: true
    },
    {
      label: "城市",
      prop: "city",
      width: 100,
      showOverflowTooltip: true
    },
    {
      label: "快递单号",
      prop: "track_number",
      width: 140,
      showOverflowTooltip: true
    },
    {
      label: "物流服务",
      prop: "shipping_service",
      width: 120,
      showOverflowTooltip: true
    },
        {
      label: "录入系统时间",
      prop: "created_at",
      width: 140,
      sortable: "custom",
      cellRenderer: ({ row }) => (
        <span>{formatDateTime(row.created_at)}</span>
      )
    },
    {
      label: "更新时间",
      prop: "updated_at",
      width: 140,
      sortable: "custom",
      cellRenderer: ({ row }) => (
        <span>{formatDateTime(row.updated_at)}</span>
      )
    }
  ]);

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage;
    form.limit = pagination.pageSize;
    form.order_type = activeTab.value; // 同步tab选择到表单

    try {
      const { data } = await mabangOrderIndex(form);

      dataList.value = data.data || [];
      searchCondList.value = data.search_cond_arr || [];
      orderStatusList.value = data.order_status_arr || [];
      shopOptionsList.value = (data as any).shop_options || [];

      // 处理tab配置和统计数据
      if ((data as any).order_type_tabs) {
        tabsList.value = (data as any).order_type_tabs;
      }
      if ((data as any).tab_counts) {
        tabCounts.value = (data as any).tab_counts;
      }

      pagination.total = data.total || 0;
      pagination.pageSize = data.per_page || 15;
      pagination.currentPage = data.current_page || 1;

    } catch (error) {
      console.error('获取订单列表失败:', error);
      message('获取订单列表失败', { type: 'error' });
      dataList.value = [];
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    selectedNum.value = val.length;
  }

  function onSelectionCancel() {
    selectedNum.value = 0;
  }

  const sortChange = (column: any) => {
    if (column.prop && column.order) {
      form.sort_field = column.prop;
      form.sort_order = column.order === 'ascending' ? 'asc' : 'desc';
    } else {
      form.sort_field = '';
      form.sort_order = '';
    }
    onSearch();
  };



  function openDialog() {
    // 预留接口，用于打开订单详情对话框
  }

  function handleDelete() {
    // 预留接口，用于删除操作
  }

   // 复制账号
   const copycontent = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message("已复制到剪贴板", { type: "success" });
    } catch (err) {
      console.error('复制失败:', err);
      // 降级处理：选中文本
      const el = document.createElement('textarea');
      el.value = content;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      message("账号已复制到剪贴板", { type: "success" });
    }
  };

  // 监听activeTab变化，同步到表单
  watch(activeTab, (newTab) => {
    form.order_type = newTab;
    pagination.currentPage = 1; // 切换tab时重置到第一页
  });

  onMounted(async () => {
    await onSearch();
    // 设置默认选中私域订单tab (value: 'private')
    const privateTab = tabsList.value.find(tab => tab.value === 'private');
    if (privateTab) {
      activeTab.value = 'private';
      // 切换tab后重新搜索以获取对应数据
      await onSearch();
    }
  });

  return {
    form,
    loading,
    columns,
    dataList,
    searchCondList,
    orderStatusList,
    shopOptionsList,
    pagination,
    selectedNum,
    // tab相关状态和方法
    activeTab,
    tabsList,
    tabCounts,
    // 详情抽屉相关方法
    openOrderDetail,
    // 其他方法
    resetForm,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    sortChange,
    openDialog,
    handleDelete
  };
}
